import Vue from 'vue'
import VueRouter from 'vue-router'
import {GetUserByTokenApi} from '../request/api'
import {SETMENU} from '../store/mutations'
import store from '@/store'
Vue.use(VueRouter)

const routes = [
  // {
  //   path: '/',
  //   component: () => import(/* webpackChunkName: "login" */ '../App.vue'),
  //   redirect:'login'
  // },
  {
    path: '/login',
    component: () => import(/* webpackChunkName: "login" */ '../views/login/Login.vue')
  },
  // {
  //   path: '/',
  //   component: () => import(/* webpackChunkName: "home" */ '../views/home/Home.vue'),
  //   children:[
    //   {
    //   path: '/good',
    // component: () => import(/* webpackChunkName: "good" */ '../views/good/Good.vue'),
    //   },
    //   {
    //   path: '/attribute',
    // component: () => import(/* webpackChunkName: "attribute" */ '../views/attribute/Attribute.vue'),
    //   }
  // ]
  // },
  
  // {
  //   path: '/',
  //   name: 'login',
  //   component: HomeView
  // },
  // {
  //   path: '/login',
  //   name: 'login',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "login" */ '../views/login/Login.vue')
  // }
]
const routesArr={
  '/good':{
    path: '/good',
  component: () => import(/* webpackChunkName: "good" */ '../views/good/Good.vue'),
    },
    '/attribute':{
    path: '/attribute',
  component: () => import(/* webpackChunkName: "attribute" */ '../views/attribute/Attribute.vue'),
    },
    '/category':{
    path: '/category',
  component: () => import(/* webpackChunkName: "category" */ '../views/category/Category.vue'),
    }
  }
 

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

const generateRoute=()=>{
  let newRoutes=[];
  //把登录后的权限菜单列表和路由进行对比,得到用户路由规则,动态添加
  for(let i=0;i<store.state.menu.length;i++){
    let path=store.state.menu[i].path
    if(routesArr[path]){
      newRoutes.push(routesArr[path])
      console.log("123",newRoutes);
    }
  }
   router.addRoute(
     {
       path: '/',
       component: () => import(/* webpackChunkName: "home" */ '../views/home/Home.vue'),
       children:newRoutes
     }
   )
}
//前置路由守卫
router.beforeEach((to,from,next)=>{
  console.log(to,from);
  let token=localStorage.getItem("token")
  if(token&&store.state.menu.length===0){
    //发送请求获取用户权限列表
    GetUserByTokenApi().then(res=>{
    //  console.log(res);
    if(res.errno===0){
      //设置vuex权限列表
     store.commit(SETMENU,res.data.menu)
     generateRoute()
    }
     next(to.path)
    })
    
  }else if(token&&store.state.menu.length>0 && from.path==='/login' &&to.path==='/home'){
    generateRoute();
    next(store.state.menu[0].path)
  }else if(!token&&to.path !=='/login'){
     next('/login')
  }else{
    next()
  }
})
export default router
